package com.web.web;


import com.web.param.AdminLoginDto;
import com.web.param.UpdatePasswordDto;
import com.web.service.IAdminService;
import com.web.util.BaseController;
import com.web.util.JsonResult;
import com.web.util.ServiceException;
import com.web.util.UploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hgjxyz
 * @since 2020-11-18
 */
@Api(tags = "管理员模块")
@RestController
@RequestMapping("/web/admin")
public class AdminController extends BaseController {

    @Autowired private IAdminService adminService;

    @ApiOperation("管理员登录")
    @PostMapping("add")
    public JsonResult<String> login(@RequestBody AdminLoginDto dto) {
        String token = this.adminService.adminLogin(dto);
        return new JsonResult<>(token);
    }

    @ApiOperation("修改密码")
    @PostMapping("update/password")
    public JsonResult<Void> addAdmin(@RequestBody UpdatePasswordDto dto) {
        this.adminService.updatePwd(dto);
        return new JsonResult<>(null);
    }

    @ApiOperation("上传文件")
    @PostMapping("upload/img")
    @CrossOrigin(origins = "*", maxAge = 3600)
    @ResponseBody
    public JsonResult<String> uploadImg(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) {
        Map<String, String> file = UploadFile.uploadSingle(picture, request, "photocache/", false);
        return new JsonResult<>(file.get("outputFile"));
    }

    @ApiOperation("下载文件")
    @PostMapping("download")
    @CrossOrigin(origins = "*", maxAge = 3600)
    public void download(@RequestParam String url, HttpServletResponse response) {
        try {
            if(url == null || url.equals("")) throw new ServiceException("请指定下载链接");
            url = "/usr/local/tomcat/webapps/" + url;
            getFile(url, response);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件流下载文件
     * @param url 文件的绝对路径
     * @param response
     * @throws ServiceException
     */
    public static void getFile(String url, HttpServletResponse response)throws ServiceException {
        String[] urlArr = url.split("\\\\");
        String fileName = urlArr[urlArr.length - 1];
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        ServletOutputStream outputStream = null;
        FileInputStream inputStream = null;
        File file = new File(url);
        //if(file.exists()) throw new ServiceException("未找到这个文件");
        try {
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int bit = 0;
            byte[] buffer = new byte[1024];
            while (bit != -1){
                bit = inputStream.read(buffer);
                if(bit != -1){
                    outputStream.write(buffer, 0, bit);
                }
            }
        } catch (FileNotFoundException e) {
            throw new ServiceException("该文件不存在或为只读文件");
        } catch (IOException e) {
            throw new ServiceException("文件读取异常");
        } finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                    inputStream = null;
                }
                if (outputStream != null){
                    outputStream.flush();
                    outputStream.close();
                    outputStream = null;
                }
            } catch (IOException e){
                throw new ServiceException("流关闭异常");
            }
        }
    }

}

